package cn.bannerplayerlibrary.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.HandlerThread;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.webkit.URLUtil;
import android.widget.FrameLayout;

import androidx.annotation.NonNull;

import com.danikula.videocache.HttpProxyCacheServer;

import java.io.IOException;
import java.util.Map;

import cn.bannerplayerlibrary.VideoCacheProxy;
import cn.bannerplayerlibrary.view.base.PlayerView;
import cn.bannerplayerlibrary.view.renderview.IRenderView;
import cn.bannerplayerlibrary.view.renderview.SurfaceRenderView;
import tv.danmaku.ijk.media.player.IMediaPlayer;
import tv.danmaku.ijk.media.player.IjkMediaPlayer;
import tv.danmaku.ijk.media.player.IjkTimedText;

public class IjkPlayerView extends FrameLayout implements PlayerView {
    private static final String TAG = "IjkPlayerView";
    private IjkMediaPlayer mIjkMediaPlayer;
    private Listener mListener;
    private Handler mHandler;
    private Uri mUri;
    //-------------------------
    // Extend: Render
    //-------------------------
    public static final int RENDER_NONE = 0;
    public static final int RENDER_SURFACE_VIEW = 1;
    public static final int RENDER_TEXTURE_VIEW = 2;
    //    private int mCurrentRender = RENDER_NONE;
    private HandlerThread mHandlerThread;
    private IRenderView mRenderView;
    private IRenderView.ISurfaceHolder mSurfaceHolder = null;

    private int mSeekWhenPrepared;  // recording the seek position while preparing
    //    private int mCurrentState = STATE_IDLE;
    private int mVideoRotationDegree;
    private int mVideoHeight;
    private int mVideoSarNum;
    private int mVideoWidth;
    private int mVideoSarDen;
    private int mSurfaceWidth;
    private int mSurfaceHeight;


    public IjkPlayerView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public IjkPlayerView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    public IjkPlayerView(Context context) {
        super(context);
        init(context);
    }

    private boolean mPlaywhenready;
    private boolean mReady;

    private void init(Context context) {
//        mCurrentState = STATE_IDLE;
        mVideoWidth = 0;
        mVideoHeight = 0;
        mReady = false;
        // REMOVED: getHolder().addCallback(mSHCallback);
        // REMOVED: getHolder().setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        setFocusable(true);
        setFocusableInTouchMode(true);
        requestFocus();
        mHandlerThread = new HandlerThread("player-control-thread");
        mHandlerThread.start();
        mHandler = new Handler(mHandlerThread.getLooper());
        setRender();
        IjkMediaPlayer.loadLibrariesOnce(null);
        IjkMediaPlayer.native_profileBegin("libijkplayer.so");

        mIjkMediaPlayer = new IjkMediaPlayer();
        IjkMediaPlayer.native_setLogLevel(IjkMediaPlayer.IJK_LOG_FATAL);
        mIjkMediaPlayer.setLogEnabled(false);

        //ijk关闭log
        resetIJkPlayer();
        mPlaywhenready = false;
        VideoCacheProxy.getProxy(context);
        setBackgroundColor(Color.BLACK);
    }

    public void setCurrentAspectRatioIndex(int currentAspectRatioIndex) {
        mCurrentAspectRatioIndex = currentAspectRatioIndex;
        mCurrentAspectRatio = s_allAspectRatio[mCurrentAspectRatioIndex];
        if (mRenderView != null) {
            mRenderView.setAspectRatio(mCurrentAspectRatio);
        }
    }

    @Override
    public void setListener(Listener listener) {
        mListener = listener;
    }

    @Override
    public void setData(String url) {
        // 获取缓存的代理地址
        if (URLUtil.isHttpsUrl(url) || URLUtil.isHttpUrl(url)) {
            mUri = Uri.parse(getProxyUrl(url));
        } else {
            mUri = Uri.parse(url);
        }
    }

    private Map<String, String> mHeaders;

    @Override
    public void seekTo(int msec) {
        mIjkMediaPlayer.seekTo(msec);
        mSeekWhenPrepared = msec;
    }

    private static final int STATE_ERROR = -1;
    private static final int STATE_IDLE = 0;
    private static final int STATE_PREPARING = 1;
    private static final int STATE_PREPARED = 2;
    private static final int STATE_PLAYING = 3;
    private static final int STATE_PAUSED = 4;
    private static final int STATE_PLAYBACK_COMPLETED = 5;
    private static final int STATE_STOP = 6;
    private static final int[] s_allAspectRatio = {
            IRenderView.AR_ASPECT_FIT_PARENT,
            IRenderView.AR_ASPECT_FILL_PARENT,
            IRenderView.AR_ASPECT_WRAP_CONTENT,
            // IRenderView.AR_MATCH_PARENT,
            IRenderView.AR_16_9_FIT_PARENT,
            IRenderView.AR_4_3_FIT_PARENT};
    private int mCurrentAspectRatioIndex = 0;
    private int mCurrentAspectRatio = s_allAspectRatio[mCurrentAspectRatioIndex];

    public int toggleAspectRatio() {
        mCurrentAspectRatioIndex++;
        mCurrentAspectRatioIndex %= s_allAspectRatio.length;

        mCurrentAspectRatio = s_allAspectRatio[mCurrentAspectRatioIndex];
        if (mRenderView != null) {
            mRenderView.setAspectRatio(mCurrentAspectRatio);
        }
        return mCurrentAspectRatio;
    }

//    private boolean isInPlaybackState() {
//        return (mIjkMediaPlayer != null &&
//                mCurrentState != STATE_ERROR &&
//                mCurrentState != STATE_IDLE &&
//                mCurrentState != STATE_PREPARING);
//    }

    private void setVideoURI(Uri uri, Map<String, String> headers) {
        mUri = uri;
        mHeaders = headers;
        mSeekWhenPrepared = 0;
        prepare();
        requestLayout();
        invalidate();
    }

    private void toPrepare() {
        mReady = false;
        if (mUri == null || mSurfaceHolder == null) {
            // not ready for playback just yet, will try again later
            return;
        }
        AudioManager am = (AudioManager) getContext().getSystemService(Context.AUDIO_SERVICE);
        am.requestAudioFocus(null, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
        resetIJkPlayer();
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                mIjkMediaPlayer.setDataSource(getContext().getApplicationContext(), mUri, null);
            } else {
                mIjkMediaPlayer.setDataSource(mUri.toString());
            }
            bindSurfaceHolder(mIjkMediaPlayer, mSurfaceHolder);
            mIjkMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
//            mIjkMediaPlayer.setScreenOnWhilePlaying(true);
            mIjkMediaPlayer.prepareAsync();
//            mCurrentState = STATE_PREPARING;
        } catch (IOException e) {
            e.printStackTrace();
//            mCurrentState = STATE_ERROR;
            if (mIjkListener != null) {
                mIjkListener.onError(mIjkMediaPlayer, MediaPlayer.MEDIA_ERROR_UNKNOWN, 0);
            }
        }
    }

    @Override
    public void prepare() {
        mHandler.removeCallbacks(mRunPrepare);
        mRunPrepare.run();
    }

    // REMOVED: mSHCallback
    private void bindSurfaceHolder(IMediaPlayer mp, IRenderView.ISurfaceHolder holder) {
        if (mp == null) {
            return;
        }

        if (holder == null) {
            mp.setDisplay(null);
            return;
        }

        holder.bindToMediaPlayer(mp);
    }

    public void setRenderView(IRenderView renderView) {
        if (mRenderView != null) {
            if (mIjkMediaPlayer != null) {
                mIjkMediaPlayer.setDisplay(null);
            }

            View renderUIView = mRenderView.getView();
            mRenderView.removeRenderCallback(mSHCallback);
            mRenderView = null;
            removeView(renderUIView);
        }

        if (renderView == null) {
            return;
        }

        mRenderView = renderView;
        mRenderView.setAspectRatio(mCurrentAspectRatio);
        if (mVideoWidth > 0 && mVideoHeight > 0) {
            mRenderView.setVideoSize(mVideoWidth, mVideoHeight);
        }
        if (mVideoSarNum > 0 && mVideoSarDen > 0) {
            mRenderView.setVideoSampleAspectRatio(mVideoSarNum, mVideoSarDen);
        }

        View renderUIView = mRenderView.getView();
        LayoutParams lp = new LayoutParams(
                LayoutParams.WRAP_CONTENT,
                LayoutParams.WRAP_CONTENT,
                Gravity.CENTER);
        renderUIView.setLayoutParams(lp);
        addView(renderUIView);

        mRenderView.addRenderCallback(mSHCallback);
        mRenderView.setVideoRotation(mVideoRotationDegree);
    }

    IRenderView.IRenderCallback mSHCallback = new IRenderView.IRenderCallback() {
        @Override
        public void onSurfaceChanged(@NonNull IRenderView.ISurfaceHolder holder, int format, int w, int h) {
            if (holder.getRenderView() != mRenderView) {
                Log.e(TAG, "onSurfaceChanged: unmatched render callback\n");
                return;
            }

            mSurfaceWidth = w;
            mSurfaceHeight = h;
//            boolean isValidState = (mCurrentState == STATE_PLAYING);
//            boolean hasValidSize = !mRenderView.shouldWaitForResize() || (mVideoWidth == w && mVideoHeight == h);
//            if (mIjkMediaPlayer != null && isValidState && hasValidSize) {
//                if (mSeekWhenPrepared != 0) {
//                    seekTo(mSeekWhenPrepared);
//                }
//                play();
//            }
        }

        @Override
        public void onSurfaceCreated(@NonNull IRenderView.ISurfaceHolder holder, int width, int height) {
            if (holder.getRenderView() != mRenderView) {
                Log.e(TAG, "onSurfaceCreated: unmatched render callback\n");
                return;
            }

            mSurfaceHolder = holder;
            if (mIjkMediaPlayer != null) {
                bindSurfaceHolder(mIjkMediaPlayer, holder);
            } else {
                prepare();
            }
        }

        @Override
        public void onSurfaceDestroyed(@NonNull IRenderView.ISurfaceHolder holder) {
            if (holder.getRenderView() != mRenderView) {
                Log.e(TAG, "onSurfaceDestroyed: unmatched render callback\n");
                return;
            }

            // after we return from this we can't use the surface any more
            mSurfaceHolder = null;
            // REMOVED: if (mMediaController != null) mMediaController.hide();
            // REMOVED: release(true);
            stop();
        }
    };

    public void setRender() {
//        switch (render) {
//            case RENDER_NONE:
//                setRenderView(null);
//                break;
//            case RENDER_TEXTURE_VIEW: {
//                TextureRenderView renderView = new TextureRenderView(getContext());
//                if (mIjkMediaPlayer != null) {
//                    renderView.getSurfaceHolder().bindToMediaPlayer(mIjkMediaPlayer);
//                    renderView.setVideoSize(mIjkMediaPlayer.getVideoWidth(), mIjkMediaPlayer.getVideoHeight());
//                    renderView.setVideoSampleAspectRatio(mIjkMediaPlayer.getVideoSarNum(), mIjkMediaPlayer.getVideoSarDen());
//                    renderView.setAspectRatio(mCurrentAspectRatio);
//                }
//                setRenderView(renderView);
//                break;
//            }
//            case RENDER_SURFACE_VIEW: {
//                SurfaceRenderView renderView = new SurfaceRenderView(getContext());
//                setRenderView(renderView);
//                break;
//            }
//            default:
//                Log.e(TAG, String.format(Locale.getDefault(), "invalid render %d\n", render));
//                break;
//        }
        SurfaceRenderView renderView = new SurfaceRenderView(getContext());
        setRenderView(renderView);
    }

    Runnable mRunPrepare = new Runnable() {
        @Override
        public void run() {
            if (mSurfaceHolder != null) {
                toPrepare();
            } else {
                mHandler.postDelayed(mRunPrepare, 2000);
            }
        }
    };

    Runnable mRunPlay = new Runnable() {
        @Override
        public void run() {
            if (mPlaywhenready) {
                if (mReady) {
                    mIjkMediaPlayer.start();
                } else {
                    mHandler.postDelayed(mRunPlay, 1);
                }
            }
//            if (mSurfaceHolder != null) {
//                if (isInPlaybackState()) {
//                    mIjkMediaPlayer.start();
//                    mCurrentState = STATE_PLAYING;
//                }
//            } else {
//                mHandler.postDelayed(mRunPlay, 2000);
//            }

        }
    };
    Runnable mRunPause = new Runnable() {
        @Override
        public void run() {
//            if (isInPlaybackState()) {
            if (mIjkMediaPlayer.isPlaying()) {
                mIjkMediaPlayer.pause();
//                    mCurrentState = STATE_PAUSED;
            }
//            }
        }
    };
    Runnable mRunStop = new Runnable() {
        @Override
        public void run() {
//            if (isInPlaybackState()) {

            removeCallbacks();
            if (mIjkMediaPlayer != null) {
                mIjkMediaPlayer.stop();
                mIjkMediaPlayer.setDisplay(null);
                mIjkMediaPlayer.reset();
//                    mCurrentState = STATE_STOP;
//                }
            }
        }
    };

    private void removeCallbacks() {
        mHandler.removeCallbacks(mRunPrepare);
        mHandler.removeCallbacks(mRunPlay);
        mHandler.removeCallbacks(mRunPause);
        mHandler.removeCallbacks(mRunStop);
    }

    private void resetIJkPlayer() {
        mIjkMediaPlayer.setDisplay(null);
        mIjkMediaPlayer.reset();
        setIjkListener(mIjkListener);
        mIjkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "start-on-prepared", 0);

        IjkMediaPlayer.native_setLogLevel(IjkMediaPlayer.IJK_LOG_FATAL);
        mIjkMediaPlayer.setLogEnabled(false);
    }

    @Override
    public void play() {
        mPlaywhenready = true;
        mHandler.removeCallbacks(mRunPlay);
        mHandler.postDelayed(mRunPlay, 300);
    }



    @Override
    public void pause() {
        mPlaywhenready = false;
        mHandler.removeCallbacks(mRunPause);
        mHandler.postDelayed(mRunPause, 300);
    }

    @Override
    public void resume() {
        play();
    }

    @Override
    public void stop() {
        mPlaywhenready = false;
        mReady = false;
        mHandler.removeCallbacks(mRunStop);
        mHandler.postDelayed(mRunStop, 300);
    }


    @Override
    public void release() {
        stop();
        if (mIjkMediaPlayer != null) {
            mIjkMediaPlayer.reset();
            mIjkMediaPlayer.setDisplay(null);
            mIjkMediaPlayer.release();
        }
        AudioManager am = (AudioManager) getContext().getSystemService(Context.AUDIO_SERVICE);
        am.abandonAudioFocus(null);
        mHandlerThread.quitSafely();
    }

    @Override
    public boolean isStarted() {
        return mPlaywhenready;
    }

    @Override
    public boolean isPlaying() {
        return mIjkMediaPlayer.isPlaying();
    }

    @Override
    public boolean isPrepared() {
        return mReady;
    }

    ///////////////////////////////////////////////////////////////

    /**
     * 获取带缓存的视频url
     *
     * @param originalUrl
     * @return
     */
    private String getProxyUrl(String originalUrl) {
        HttpProxyCacheServer proxy = VideoCacheProxy.getProxy(getContext());
        return proxy.getProxyUrl(originalUrl);
    }

    private IjkPlayerListener mIjkListener = new BaseIjkPlayerListener() {

        @Override
        public void onPrepared(IMediaPlayer mp) {
//            mCurrentState = STATE_PREPARED;
            // Get the capabilities of the player for this stream
            // REMOVED: Metadata
            mReady = true;
            if (mListener != null) {
                mListener.onPrepared(IjkPlayerView.this);
            }
            mVideoWidth = mp.getVideoWidth();
            mVideoHeight = mp.getVideoHeight();
//            int seekToPosition = mSeekWhenPrepared;  // mSeekWhenPrepared may be changed after seekTo() call
//            if (seekToPosition != 0) {
//                seekTo(seekToPosition);
//            }
            if (mVideoWidth != 0 && mVideoHeight != 0) {
                if (mRenderView != null) {
                    mRenderView.setAspectRatio(mCurrentAspectRatio);
                    mRenderView.setVideoSize(mVideoWidth, mVideoHeight);
                    mRenderView.setVideoSampleAspectRatio(mVideoSarNum, mVideoSarDen);
                }
            }

        }

        @Override
        public void onVideoSizeChanged(IMediaPlayer mp, int i, int i1, int i2, int i3) {
            mVideoWidth = mp.getVideoWidth();
            mVideoHeight = mp.getVideoHeight();
            mVideoSarNum = mp.getVideoSarNum();
            mVideoSarDen = mp.getVideoSarDen();
            if (mVideoWidth != 0 && mVideoHeight != 0) {
                if (mRenderView != null) {
                    mRenderView.setAspectRatio(mCurrentAspectRatio);
                    mRenderView.setVideoSize(mVideoWidth, mVideoHeight);
                    mRenderView.setVideoSampleAspectRatio(mVideoSarNum, mVideoSarDen);
                }
                // REMOVED: getHolder().setFixedSize(mVideoWidth, mVideoHeight);
                requestLayout();
            }
        }

        @Override
        public void onCompletion(IMediaPlayer iMediaPlayer) {
//            mCurrentState = STATE_PLAYBACK_COMPLETED;
            if (mListener != null) {
                mListener.onCompleted(IjkPlayerView.this);
            }
        }

        @Override
        public boolean onError(IMediaPlayer iMediaPlayer, int i, int i1) {
//            mCurrentState = STATE_ERROR;
            if (mListener != null) {
                mListener.onError(IjkPlayerView.this);
            }
            return true;
        }

        @Override
        public boolean onInfo(IMediaPlayer iMediaPlayer, int arg1, int arg2) {
            switch (arg1) {
                case IMediaPlayer.MEDIA_INFO_VIDEO_TRACK_LAGGING:
                    Log.d(TAG, "MEDIA_INFO_VIDEO_TRACK_LAGGING:");
                    break;
                case IMediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START:
                    Log.d(TAG, "MEDIA_INFO_VIDEO_RENDERING_START:");
                    break;
                case IMediaPlayer.MEDIA_INFO_BUFFERING_START:
                    Log.d(TAG, "MEDIA_INFO_BUFFERING_START:");
                    break;
                case IMediaPlayer.MEDIA_INFO_BUFFERING_END:
                    Log.d(TAG, "MEDIA_INFO_BUFFERING_END:");
                    break;
                case IMediaPlayer.MEDIA_INFO_NETWORK_BANDWIDTH:
                    Log.d(TAG, "MEDIA_INFO_NETWORK_BANDWIDTH: " + arg2);
                    break;
                case IMediaPlayer.MEDIA_INFO_BAD_INTERLEAVING:
                    Log.d(TAG, "MEDIA_INFO_BAD_INTERLEAVING:");
                    break;
                case IMediaPlayer.MEDIA_INFO_NOT_SEEKABLE:
                    Log.d(TAG, "MEDIA_INFO_NOT_SEEKABLE:");
                    break;
                case IMediaPlayer.MEDIA_INFO_METADATA_UPDATE:
                    Log.d(TAG, "MEDIA_INFO_METADATA_UPDATE:");
                    break;
                case IMediaPlayer.MEDIA_INFO_UNSUPPORTED_SUBTITLE:
                    Log.d(TAG, "MEDIA_INFO_UNSUPPORTED_SUBTITLE:");
                    break;
                case IMediaPlayer.MEDIA_INFO_SUBTITLE_TIMED_OUT:
                    Log.d(TAG, "MEDIA_INFO_SUBTITLE_TIMED_OUT:");
                    break;
                case IMediaPlayer.MEDIA_INFO_VIDEO_ROTATION_CHANGED:
                    mVideoRotationDegree = arg2;
                    Log.d(TAG, "MEDIA_INFO_VIDEO_ROTATION_CHANGED: " + arg2);
                    if (mRenderView != null) {
                        mRenderView.setVideoRotation(arg2);
                    }
                    break;
                case IMediaPlayer.MEDIA_INFO_AUDIO_RENDERING_START:
                    Log.d(TAG, "MEDIA_INFO_AUDIO_RENDERING_START:");
                    break;
            }
            return super.onInfo(iMediaPlayer, arg1, arg2);
        }
    };

    public void setIjkListener(IjkPlayerListener listener) {
        if (mIjkMediaPlayer != null) {
            mIjkMediaPlayer.setOnPreparedListener(listener);
            mIjkMediaPlayer.setOnVideoSizeChangedListener(listener);
            mIjkMediaPlayer.setOnCompletionListener(listener);
            mIjkMediaPlayer.setOnErrorListener(listener);
            mIjkMediaPlayer.setOnInfoListener(listener);
            mIjkMediaPlayer.setOnBufferingUpdateListener(listener);
            mIjkMediaPlayer.setOnSeekCompleteListener(listener);
            mIjkMediaPlayer.setOnTimedTextListener(listener);
        }
    }

    public interface IjkPlayerListener
            extends IMediaPlayer.OnPreparedListener, IMediaPlayer.OnVideoSizeChangedListener,
            IMediaPlayer.OnCompletionListener, IMediaPlayer.OnErrorListener,
            IMediaPlayer.OnInfoListener, IMediaPlayer.OnBufferingUpdateListener,
            IMediaPlayer.OnSeekCompleteListener, IMediaPlayer.OnTimedTextListener {

        @Override
        void onPrepared(IMediaPlayer iMediaPlayer);

        @Override
        void onVideoSizeChanged(IMediaPlayer iMediaPlayer, int i, int i1, int i2, int i3);

        @Override
        void onCompletion(IMediaPlayer iMediaPlayer);

        @Override
        boolean onError(IMediaPlayer iMediaPlayer, int i, int i1);

        @Override
        boolean onInfo(IMediaPlayer iMediaPlayer, int i, int i1);

        @Override
        void onBufferingUpdate(IMediaPlayer iMediaPlayer, int i);

        @Override
        void onSeekComplete(IMediaPlayer iMediaPlayer);

        @Override
        void onTimedText(IMediaPlayer iMediaPlayer, IjkTimedText ijkTimedText);
    }

    public static class BaseIjkPlayerListener implements IjkPlayerListener {

        @Override
        public void onPrepared(IMediaPlayer iMediaPlayer) {

        }

        @Override
        public void onVideoSizeChanged(IMediaPlayer iMediaPlayer, int i, int i1, int i2, int i3) {

        }

        @Override
        public void onCompletion(IMediaPlayer iMediaPlayer) {

        }

        @Override
        public boolean onError(IMediaPlayer iMediaPlayer, int i, int i1) {
            return false;
        }

        @Override
        public boolean onInfo(IMediaPlayer iMediaPlayer, int i, int i1) {
            return false;
        }

        @Override
        public void onBufferingUpdate(IMediaPlayer iMediaPlayer, int i) {

        }

        @Override
        public void onSeekComplete(IMediaPlayer iMediaPlayer) {

        }

        @Override
        public void onTimedText(IMediaPlayer iMediaPlayer, IjkTimedText ijkTimedText) {

        }
    }
}
